<template>
    <div class="app-container">
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <h2 class="card-title">导入档案</h2>
        </div>
  
        <div class="content-wrapper">
          <!-- 添加Tab组件 -->
          <el-tabs v-model="activeTab" type="card">
            <el-tab-pane label="服务器路径指定" name="ftp">
              <!-- 服务器路径上传方式 -->
              <div class="upload-section server-path-section">
                <div class="section-title">
                  <i class="el-icon-folder-opened"></i> 服务器文件路径配置
                </div>
                
                <div class="path-tip-box">
                  <i class="el-icon-info tip-icon"></i>
                  <div class="path-tip-content">
                    <div class="path-tip-title">路径说明</div>
                    <div class="path-tip-text">请输入已在服务器上的全宗的文件夹路径（文件夹名称包含全宗号、文件夹内包含"文书"文件夹）</div>
                  </div>
                </div>
                
                <el-form :model="ftpFormData" ref="ftpFormRef" label-width="120px" class="ftp-form">
                  <el-form-item label="服务器路径" prop="serverPath">
                    <el-input 
                      v-model="ftpFormData.serverPath" 
                      placeholder="请输入服务器上的文件夹路径" 
                      prefix-icon="el-icon-folder" 
                      clearable
                      class="path-input">
                    </el-input>
                  </el-form-item>
                  <el-form-item class="btn-center">
                    <el-button type="primary" @click="handleConfirmPath" icon="el-icon-check" size="medium" class="process-button" :loading="isConfirmingPath">
                      {{ isConfirmingPath ? '确认中...' : '确认路径' }}
                    </el-button>
                  </el-form-item>
                </el-form>
                
                <div class="path-example">
                  <div class="example-title"><i class="el-icon-document"></i> 路径示例：</div>
                  <div class="example-content">/home/data/NJ03</div>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="文件上传" name="file">
              <!-- 原有上传组件 -->
              <div class="upload-section">
                <el-upload ref="upload" action="/upload" :auto-upload="true" :on-success="handleSuccess"
                  :on-error="handleError" :before-upload="beforeUpload" :http-request="customUpload" :file-list="fileList"
                  :limit="1" :on-progress="handleProgress" :on-remove="handleRemove" class="upload-component">
                  <el-button slot="trigger" type="primary" :disabled="fileList.length >= 1" size="medium"
                    icon="el-icon-upload">
                    选择文件
                  </el-button> 
                  <div slot="tip" class="el-upload__tip">将一个全宗的文件夹（文件夹名称包含全宗号、文件夹内包含"文书"文件夹）打包压缩为ZIP后在此上传，支持上传超大文件，请耐心等待。</div>
                </el-upload>
      
                <!-- 进度条 -->
                <div v-if="uploadProgress" class="progress-container">
                  <el-progress :percentage="uploadProgress" :text-inside="true" :color="progressBarColor" :stroke-width="15"
                    class="progress-bar" />
                  <div class="progress-status">
                    <el-tag size="small"
                      :type="uploadStatus === 'success' ? 'success' : uploadStatus === 'error' ? 'danger' : 'primary'">
                      {{ uploadStatus === 'success' ? '上传完成' : uploadStatus === 'error' ? '上传失败' : '上传中...' }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
  
          <!-- 文件列表和操作 -->
          <div class="file-info-section">
            <div v-if="fileList.length > 0" class="file-list-container">
              <div class="section-title">文件详情</div>
  
              <el-table :data="fileList" style="width: 100%" border
                :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
                <el-table-column prop="name" label="文件名称" min-width="220" />
                <el-table-column prop="size" label="文件大小" width="140" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.size === '-' ? '-' : formatFileSize(scope.row.size) }}
                  </template>
                </el-table-column>
                <el-table-column label="状态" width="120" align="center">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 'success' ? 'success' : 'warning'" size="medium" effect="dark">
                      {{ scope.row.status === 'success' ? '已上传' : '上传中' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)" :disabled="uploadProgress > 0"
                      icon="el-icon-delete">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
  
            <!-- 全宗号输入框 -->
            <div class="processing-section">
              <div class="section-title">文档处理</div>
  
              <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px" class="processing-form">
                <el-form-item label="任务名称" prop="name">
                  <el-input v-model="formData.name" placeholder="请输入任务名称" :disabled="isProcessing"
                    prefix-icon="el-icon-s-order" clearable></el-input>
                </el-form-item>
                <el-form-item label="全宗号" prop="fondCode">
                  <el-input v-model="formData.fondCode" placeholder="请输入全宗号" :disabled="isProcessing"
                    prefix-icon="el-icon-document" clearable></el-input>
                </el-form-item>
  
                <el-form-item class="btn-center">
                  <el-button type="primary" :disabled="!canProcess || isProcessing" @click="handleProcess"
                    icon="el-icon-check" size="medium" class="process-button" :loading="isProcessing">
                    {{ isProcessing ? '处理中...' : '开始处理文档' }}
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { uploadApi } from '@/api/upload'
  import { Api } from '@/api/upload'
  
  export default {
    data() {
      return {
        activeTab: 'ftp', // 默认选中服务器路径上传标签页
        ftpFormData: {
          serverPath: ''
        },
        isConfirmingPath: false, // 新增确认路径状态
        fileList: [], // 存储上传的文件列表
        filePath: '',
        uploadProgress: 0, // 上传进度
        chunkSize: 1024 * 1024 * 0.8, // 每次上传的文件块大小，0.8MB
        uploadStatus: 'normal', // 上传状态：normal, success, error
        isProcessing: false, // 是否正在处理文档
        currentFile: null, // 当前正在上传的文件信息
        uploadingMessage: null, // 用于存储上传中的消息实例
        formData: {
          fondCode: '',
          name: ''
        },
        rules: {
          fondCode: [
            { required: true, message: '请输入全宗号', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入任务名称', trigger: 'blur' }
          ]
        }
      };
    },
    computed: {
      canProcess() {
        return this.fileList.length > 0 && this.fileList.every(file => file.status === 'success');
      },
      progressBarColor() {
        if (this.uploadStatus === 'success') return '#67c23a';
        if (this.uploadStatus === 'error') return '#f56c6c';
        return '#409EFF'; // 默认蓝色
      }
    },
    methods: {
      formatFileSize(size) {
        if (size < 1024) {
          return size + ' B';
        } else if (size < 1024 * 1024) {
          return (size / 1024).toFixed(2) + ' KB';
        } else if (size < 1024 * 1024 * 1024) {
          return (size / (1024 * 1024)).toFixed(2) + ' MB';
        } else {
          return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
        }
      },
  
      beforeUpload(file) {
        const maxSize = 1024 * 1024 * 1500000;  // 设置最大文件大小（1500000MB）
        if (file.size > maxSize) {
          this.$message.error('文件大小不能超过 1500000MB');
          return false;
        }
        this.currentFile = {
          name: file.name,
          size: file.size,
          status: 'uploading'
        };
        this.uploadStatus = 'normal';
        return true;
      },
  
      handleProgress(event, file, fileList) {
        this.uploadProgress = Math.round((event.loaded / event.total) * 100);
        this.uploadStatus = this.uploadProgress === 100 ? 'success' : 'normal';
      },
  
      handleSuccess(response, file, fileList) {
        this.$message.success('文件上传成功');
        this.uploadProgress = 0;
        this.uploadStatus = 'success';
        if (this.currentFile) {
          this.currentFile.status = 'success';
          this.fileList = [this.currentFile];
        }
      },
  
      handleError(error, file, fileList) {
        this.$message.error('文件上传失败');
        this.uploadProgress = 0;
        this.uploadStatus = 'error';
        if (this.currentFile) {
          this.currentFile.status = 'error';
        }
      },
  
      handleDelete(file) {
        this.$confirm('确认删除该文件吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 判断是否是服务器路径上传方式（文件大小为'-'）
          if (file.size === '-') {
            // 服务器路径上传，不需要调用删除API
            this.fileList = this.fileList.filter(item => item !== file);
            this.$message.success('删除成功');
            // 删除成功后重置状态
            this.filePath = '';
            this.currentFile = null;
          } else {
            // 文件上传方式，需要调用删除文件的API
            Api('deleteFile', {
              filePath: this.filePath,
              fileName: file.name,
              fileSize: file.size
            }).then(response => {
              if (response.code === 200) {
                this.fileList = this.fileList.filter(item => item !== file);
                this.$message.success('删除成功');
                // 删除成功后重置上传状态
                this.filePath = '';
                this.currentFile = null;
              } else {
                this.$message.error(response.message || '删除失败');
              }
            }).catch(error => {
              console.error('删除文件失败:', error);
              this.$message.error('删除失败');
            });
          }
        }).catch(() => {
          // 用户取消删除操作
        });
      },
  
      handleRemove(file, fileList) {
        // 如果文件已经上传成功，则需要调用API删除
        if (file.status === 'success' && this.filePath) {
          // 判断是否是服务器路径上传
          if (this.activeTab === 'ftp' || file.size === '-') {
            // 服务器路径上传不需要调用删除文件API
            this.$message.success('文件已删除');
            // 重置状态
            this.filePath = '';
            this.currentFile = null;
          } else {
            Api('deleteFile', {
              filePath: this.filePath,
              fileName: file.name,
              fileSize: file.size
            }).then(response => {
              if (response.code === 200) {
                this.$message.success('文件已删除');
                // 重置状态
                this.filePath = '';
                this.currentFile = null;
              } else {
                this.$message.error(response.message || '删除失败');
              }
            }).catch(error => {
              console.error('删除文件失败:', error);
              this.$message.error('删除失败');
            });
          }
        }
        this.fileList = fileList;
      },
  
      handleProcess() {
        if (!this.canProcess) return;
  
        // 表单验证
        this.$refs.formRef.validate(valid => {
          if (!valid) {
            this.$message.warning('请填写正确的全宗号');
            return;
          }
  
          this.isProcessing = true;
  
          // 获取文件信息和全宗号
          const fileInfo = this.fileList[0];
          const fondCode = this.formData.fondCode;
          const name = this.formData.name;
  
          // 这里添加处理文档的API调用，传递全宗号参数
          // 示例: 调用API
          Api('processDocument', {
            filePath: this.filePath,
            fondCode: fondCode,
            name: name ,
            type: this.activeTab === 'ftp' ? 'ftp' : 'file'
          }).then(response => {
            if (response.code === 200) {
              this.$message.success(response.message);
  
            } else {
              this.$message.error(response.message || '文档处理失败');
            }
          }).catch(error => {
            console.error('处理文档出错:', error);
            this.$message.error('文档处理失败');
          }).finally(() => {
            this.isProcessing = false;
          });
        });
      },
  
      customUpload(options) {
        const file = options.file;
        const totalChunks = Math.ceil(file.size / this.chunkSize);
        var chunkFile = 0;
  
        // 显示上传中的消息
        this.uploadingMessage = this.$message({
          message: '文件上传中...',
          duration: 0,
          type: 'info'
        });
  
        const uploadChunk = async (chunkIndex) => {
          const start = chunkIndex * this.chunkSize;
          const end = Math.min(start + this.chunkSize, file.size);
          const blob = file.slice(start, end);
  
          console.log(`Blob size: ${blob.size} bytes`);
  
          const formData = new FormData();
          formData.append('file', blob);
          formData.append('filename', file.name);
          formData.append('chunk', chunkIndex);
          formData.append('totalChunks', totalChunks);
  
          try {
            const res = await uploadApi(formData, {
              onUploadProgress: (progressEvent) => {
                chunkFile = progressEvent.total + chunkFile;
                this.uploadProgress = Math.round((chunkFile / file.size) * 100);
                this.uploadStatus = 'normal';
              }
            });
  
            // 不处理每个分片的成功消息
            console.log(`Chunk ${chunkIndex + 1}/${totalChunks} uploaded`);
  
            if (chunkIndex + 1 < totalChunks) {
              await uploadChunk(chunkIndex + 1);  // 递归上传下一个块
            } else {
              // 所有分片上传完成后，关闭上传中消息，显示上传成功
              if (this.uploadingMessage) {
                this.uploadingMessage.close();
              }
              this.$message.success('文件上传完成');
              this.uploadProgress = 0;
              this.uploadStatus = 'success';
  
  
              this.filePath = res.data
  
              if (this.currentFile) {
                this.currentFile.status = 'success';
                this.fileList = [this.currentFile];
              }
            }
          } catch (error) {
            // 发生错误时，关闭上传中消息，显示错误信息
            if (this.uploadingMessage) {
              this.uploadingMessage.close();
            }
            this.$message.error('上传失败');
            this.uploadStatus = 'error';
            if (this.currentFile) {
              this.currentFile.status = 'error';
            }
            throw error; // 向上传递错误
          }
        };
  
        uploadChunk(0).catch(err => {
          // 发生错误时，确保关闭上传中消息
          if (this.uploadingMessage) {
            this.uploadingMessage.close();
          }
          this.uploadStatus = 'error';
          console.error(err);
        });
      },
  
      // 修改确认路径方法
      handleConfirmPath() {
        if (!this.ftpFormData.serverPath) {
          this.$message.warning('请输入服务器上的文件夹路径');
          return;
        }
        
        this.isConfirmingPath = true;
        
        // 模拟网络延迟，实际项目中可以替换为真实API调用
        setTimeout(() => {
          // 将服务器路径保存到filePath
          this.filePath = this.ftpFormData.serverPath;
          
          // 创建一个虚拟的文件对象以显示在文件列表中
          const fileName = this.filePath.split('/').pop() || '服务器文件夹';
          this.currentFile = {
            name: fileName,
            size: '-', // 将大小设为'-'而不是0
            status: 'success'
          };
          this.fileList = [this.currentFile];
          
          this.$message({
            message: '文件夹路径已确认',
            type: 'success',
            duration: 2000
          });
          
          this.isConfirmingPath = false;
        }, 600);
      },
    },
  };
  </script>
  
  <style scoped>
  .app-container {
    padding: 20px;
    min-height: calc(100vh - 84px);
    background-color: #f5f7fa;
  }
  
  .box-card {
    margin-bottom: 20px;
    min-height: calc(100vh - 124px);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }
  
  .card-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
  
  .content-wrapper {
    padding: 10px 0;
  }
  
  .upload-section {
    background-color: #fafafa;
    border-radius: 8px;
    padding: 30px;
    margin-bottom: 20px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    transition: all 0.3s;
  }
  
  .upload-section:hover {
    border-color: #409EFF;
  }
  
  .upload-component {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .progress-container {
    margin-top: 20px;
    width: 80%;
    margin-left: auto;
    margin-right: auto;
  }
  
  .progress-status {
    margin-top: 10px;
    text-align: center;
  }
  
  .progress-bar {
    width: 100%;
  }
  
  .el-upload__tip {
    color: #909399;
    margin-top: 15px;
    font-size: 14px;
  }
  
  .file-info-section {
    margin-top: 30px;
  }
  
  .file-list-container {
    margin-bottom: 30px;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .processing-section {
    margin-top: 30px;
  }
  
  .processing-form {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #fafafa;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .el-form-item:last-child {
    margin-bottom: 0;
  }
  
  .btn-center {
    text-align: center !important;
  }
  
  .process-button {
    padding-left: 25px;
    padding-right: 25px;
    font-weight: 500;
  }
  
  .el-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
  }
  
  /* 响应式调整 */
  @media (max-width: 768px) {
    .processing-form {
      padding: 15px;
      max-width: 100%;
    }
  
    .upload-section {
      padding: 20px;
    }
  
    .progress-bar {
      width: 100%;
    }
  }
  
  .ftp-form {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
    background-color: #fafafa;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  /* 调整Tab样式 */
  .el-tabs__item {
    font-size: 15px;
    height: 46px;
    line-height: 46px;
  }
  
  .el-tabs__header {
    margin-bottom: 25px;
  }
  
  .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
    border-bottom-color: #fff;
    background-color: #f5f7fa;
    font-weight: 500;
  }
  
  /* 新增美化样式 */
  .server-path-section {
    background-color: #f8fbff;
    border: 1px dashed #a3d0fd;
  }
  
  .section-title {
    display: flex;
    align-items: center;
  }
  
  .section-title i {
    margin-right: 8px;
    font-size: 18px;
    color: #409EFF;
  }
  
  .path-tip-box {
    display: flex;
    background-color: #ecf8ff;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 25px;
    border-left: 4px solid #50bfff;
  }
  
  .tip-icon {
    color: #409EFF;
    font-size: 18px;
    margin-right: 10px;
    margin-top: 2px;
  }
  
  .path-tip-content {
    flex: 1;
  }
  
  .path-tip-title {
    font-weight: 600;
    margin-bottom: 5px;
    color: #303133;
    font-size: 14px;
  }
  
  .path-tip-text {
    color: #606266;
    line-height: 1.6;
    font-size: 13px;
  }
  
  .path-input {
    font-size: 14px;
  }
  
  .path-example {
    background-color: #f5f7fa;
    padding: 12px 16px;
    border-radius: 6px;
    margin-top: 15px;
    font-size: 13px;
  }
  
  .example-title {
    color: #606266;
    font-weight: 600;
    margin-bottom: 8px;
  }
  
  .example-title i {
    margin-right: 5px;
  }
  
  .example-content {
    color: #909399;
    font-family: monospace;
    padding: 8px;
    background-color: #ffffff;
    border-radius: 4px;
    border: 1px dashed #e0e0e0;
  }
  
  .confirm-button {
    min-width: 120px;
    font-weight: 500;
    transition: all 0.3s;
  }
  
  .confirm-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
  </style>

<!-- 全局样式，不使用scoped -->
<style>
/* 调整Tab样式 */
.el-tabs__item {
  font-size: 15px;
  height: 46px;
  line-height: 46px;
}

.el-tabs__header {
  margin-bottom: 25px;
}

.el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  border-bottom-color: #fff;
  background-color: #f5f7fa;
  font-weight: 500;
}
</style>